<template>
  <a-modal :visible="visible" title="视频提取文案" :zIndex="1001" centered :width="600" @cancel="onClose" :footer="null"
    :body-style="{
      padding: '16px',
    }">
    <div class="ai-wirting mt-20">
      <a-form layout="horizontal">
        <a-form-item label="视频来源">
          <a-radio-group v-model:value="radioValue">
            <a-radio :value="1"> 网络视频 </a-radio>
            <a-radio :value="2"> 素材库视频 </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="视频链接" v-if="radioValue == 1">
          <a-textarea v-model:value="internetVideoUrl" placeholder="请粘贴抖音视频链接，视频时长建议不超过20分钟" style="
              width: 450px;
              height: 100px;
              resize: none;
              border-radius: 5px;
            "></a-textarea>
        </a-form-item>
        <a-form-item label="视频素材" v-if="radioValue == 2">
          <a-card v-if="!currentVideo?.material_url">
            <div class="upload-wrapper">
              <div class="upload-content" @click="debouncedClick">
                <cloud-upload-outlined />
                <span class="text-16 text-gray-5">添加视频</span>
              </div>
            </div>
          </a-card>
          <div class="video_con" v-else>
            <video id="videoPlayer" :src="currentVideo?.material_url" autoplay />
            <div class="operate_con">
              <cu-icon @click="deleteVideo" type="icon-shanchu1" class="delete_icon" />
            </div>
          </div>
        </a-form-item>
      </a-form>
      <div style="margin: 0 0 80px 70px">
        <a-button type="primary" :loading="submitLoading" @click="handleExtract">开始提取</a-button>
        <div class="text-gray-5 mt-5">
          当前剩余{{ name_unit }}{{ residue_count
          }}{{ unit }},（每分钟消耗{{ consumes }}{{ unit }}{{ name_unit }},
          不足1分钟按1分钟计算）
                </div>
      </div>
    </div>

    <ChooseMaterial :isClip="false" material_type="video" :visible="chooseVisible" @close="closeChoose" />
  </a-modal>

  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>
</template>

<script setup>
import {
  reactive,
  toRefs,
  watch,
  computed,
  ref,
  watchEffect,
  nextTick,
  onUnmounted,
} from "vue";
import { CloudUploadOutlined, PlusOutlined } from "@ant-design/icons-vue";
import request from "@/common/utils/request.js";
import { useRouter } from "vue-router";
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import store from "@/store/index.js";
import { debounce } from "lodash";
import utils from "@/common/utils/utils.js";
import { message, notification } from "ant-design-vue";

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)
const emit = defineEmits(["cancel", "success_Sub:data"]);
// TODO 视频提取文字

const props = defineProps({
  visible: {
    type: Boolean,
    default: true,
  },
});

const onClose = () => {
  internetVideoUrl.value = ''
  submitLoading.value = false
  emit("cancel");
};

const router = useRouter();
const radioValue = ref(1);
const internetVideoUrl = ref("");
const chooseVisible = ref(false);
const currentVideo = ref({});
const submitLoading = ref(false);
const residue_count = ref(0);
const debounceTimer = ref(null);
// 开始提取
const handleExtract = async() => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
    vipVisible.value = true
  } else {
    if (radioValue.value == 1 && !internetVideoUrl.value) {
      message.warn("请先粘贴视频链接");
      return;
    }

    if (radioValue.value == 2 && JSON.stringify(currentVideo.value) == "{}") {
      message.warn("请先从素材库选择视频");
      return;
    }
    
    if (radioValue.value == 2) {
      try {
        const number = utils.getT(currentVideo.value?.material_duration)
        const res = await utils.videoConverTextConfig({
          number
        })
        // 查询积分, 积分不足则走不到这一步
        // 获取积分消耗提示内容
        const content = utils.useText(res)
        try {
          // 确认消耗
          await utils.kd({ content,res })
        } catch (error) {
          return
        }
      } catch (error) {
        // 打开充值, 接着打开点数购买
        vipVisible.value = true
        vipModalRef.value && vipModalRef.value.openBuyVisible()
        return
      }
    }
    submitLoading.value = true;

    

    let params = {
      script_typeuser: "user",
      video_source: radioValue.value == 1 ? "internet" : "material",
      video_url:
        radioValue.value == 1
          ? internetVideoUrl.value
          : currentVideo.value?.material_url,
      merchant_folder_statck_multimedia_id:
        radioValue.value == 1
          ? 0
          : currentVideo.value?.merchant_folder_statck_id,
    };

    request
      .post("/work_ai", "/user/shotstack/video/conver/text/add", params)
      .then((res) => {
        if (res?.code && res?.code != 1000) return message.error(res?.msg);

        submitLoading.value = false;

        let data = {
          id: res.id,
          source: radioValue.value == 1 ? "2" : "3",
        };
        emit("success_Sub", JSON.parse(JSON.stringify(data)));
      })
      .catch((err) => {
        submitLoading.value = false;
      });
  }
};

const showOpenMaterialModal = () => {
  chooseVisible.value = true;
};
const closeChoose = (obj) => {
  chooseVisible.value = false;
  if (obj) {
    currentVideo.value = obj;
    console.log(obj,'选择的素材');
    
  }
};

const playVideo = () => {
  document.getElementById("videoPlayer").play();
};

const deleteVideo = () => {
  currentVideo.value = {};
};

const unit = ref("");
const unit_name = ref("");
const consumes = ref("");
const numberInfo_unit = ref("");

// 查询点数
const getCount = (data={}) => {
  const { init = false, number=1 } = data
  return new Promise(async (resolve, reject) => {
    const res = await request
      .get("/work_ai", "/user/shotstack/video/conver/text/config", {
        number,
      })
        residue_count.value = res.pointInfo.current;
        consumes.value = res.pointInfo.consumes;
        unit.value = res.pointInfo.unit;
        unit_name.value = res.pointInfo.name;
    numberInfo_unit.value = res.numberInfo.unit;
  
    if (res.usable != 1 && !init) {
      vipVisible.value = true;
     return reject(false)
    }
    resolve(true)
  });
  
};

getCount({init:true, number:1});

// 防抖
const debouncedClick = () => {
  if (store.getters.isVersionExpired) {
    notification.warn({ message: "您的套餐已到期", duration: 2 });
    vipVisible.value = true
  } else {
    if (debounceTimer.value) {
      clearTimeout(debounceTimer.value);
    }

    debounceTimer.value = setTimeout(() => {
      showOpenMaterialModal();
    }, 500);
  }
};

// onUnmounted(() => {
//   if (timeoutId.value) {
//     clearTimeout(timeoutId.value);
//     timeoutId.value = null;
//   }
// });
</script>

<style lang="less" scoped>
.ai-wirting {
  // height: 400px;
}

.video_con {
  width: 150px;
  height: 250px;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .operate_con {
    display: none;
  }

  &:hover {
    .operate_con {
      width: 150px;
      height: 250px;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;

      .play_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }

      .delete_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }
    }
  }

  video {
    max-width: 100%;
    max-height: 100%;
  }
}

// .smart-clip {
//   padding: 14px 14px 0;
//   height: 100%;
//   box-sizing: border-box;
// }

.ant-input-number {
  border-radius: 5px;
}

button {
  border-radius: 5px;
}

:deep(.ant-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.textarea-wrapper {
  border-radius: 5px;
}

input {
  border-radius: 5px;
}

:deep(.ant-card) {
  border-radius: 15px;
}

.upload-wrapper {
  width: 200px;
  height: 324px;
  margin: 0 20px 20px 0;
  padding: 20px;
  background-color: #f3f4f6;
  border-radius: 15px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 46px;
  width: 160px;
  height: 284px;
  background-color: #fff;
  border-radius: 15px;
  cursor: pointer;
}

.text-16 {
  font-size: 16px;
}
</style>
